window.ReactWebComponent = $.extend(window.ReactWebComponent, (function () {

    var Dropdown = React.createClass({
        loadData: function () {
            var _this = this;
            if (_this.props.get.result){
                _this.setState({ data: _this.props.get.result });
                return;
            }
            $.ajax({
                url: _this.props.get.url,
                type: "GET",
                data: _this.props.get.data,
                dataType: "json",
                cache: false,
                success: function (data) {
                    if (/success/i.test(data.ResultCode)){
                        _this.setState({data: data.Data});
                    }
                },
                error: function (xhr, status, err) {
                    console.error(_this.props.get.url, status, err.toString());
                }
            });
        },
        handleItemClick: function (item) {
            $(this.refs.input).val($(item).data("value"));
            this.props.onItemClick && this.props.onItemClick.call(item)
        },
        getInitialState: function () {
            return {data: []};
        },
        componentDidMount: function () {
            this.loadData();
        },
        render: function () {
            return (
                <div className="btn-group" role="select">
                    <button type="button" className="btn btn-default" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" role="selecteditem">{this.props.defaultText}</button>
                    <button type="button" className="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                        <span className="caret"></span>
                    </button>
                    <DropdownList data={this.state.data} onItemClick={this.handleItemClick} />
                    <input id={this.props.id} ref="input" type="hidden" />
                </div>
            );
        }
    });

    var DropdownList = React.createClass({
        render: function () {
            var that = this;
            var items = this.props.data.map(function (item) {
                return (
                    <li key={item.ID}>
                        <DropdownListItem value={item.Value} text={item.Text} onItemClick={that.props.onItemClick} />
                    </li>
                )
            });
            return (
                <ul className="dropdown-menu">
                    { items }
                </ul>
            )
        }
    });

    var DropdownListItem = React.createClass({
        handleClick: function () {
            this.props.onItemClick(this.refs.item);
        },
        render: function () {
            return (
                <a ref="item" href="javascript:;" onClick={this.handleClick} data-value={this.props.value}>{this.props.text}</a>
            )
        }
    });

    return {
        Dropdown: Dropdown
    }

})());